package hu.kisprof.quizServer.model.bean;

import hu.kisprof.quiz.model.bean.Player;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;

public class Room {
	private String name;
	private Map<String,Player> players = new HashMap<String,Player>();
	private int numberOfPlayers = 0;
	
	
	
	public Room(String name){
		this.name=name;
	}
	
	public Room(String name,Player ply){
		this(name);
		addPlayer(ply);
	}
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + numberOfPlayers;
		result = prime * result + ((players == null) ? 0 : players.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Room other = (Room) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (numberOfPlayers != other.numberOfPlayers)
			return false;
		if (players == null) {
			if (other.players != null)
				return false;
		} else if (!players.equals(other.players))
			return false;
		return true;
	}

	public boolean isPlayerInRoom(Player ply){
		return isPlayerInRoom(ply.getUsername());
	}
	
	public boolean isPlayerInRoom(String username){
		return players.containsKey(username);
	}

	public void addPlayer(Player ply){
		players.put(ply.getUsername(),ply);
		numberOfPlayers++;
	}
	
	public boolean removePlayer(Player ply){
		if(players.remove(ply.getUsername()) != null){
			--numberOfPlayers;
			return true;
		}
		return false;
	}	
	
	public String getName() {
		return name;
	}

	public int getNumberOfPlayers() {
		return numberOfPlayers;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public String toString(){
		return ""+this.name+"("+this.numberOfPlayers+")";
		
	}

	public TreeSet<String> getPlayers() {
		return new TreeSet<String>(players.keySet());
	}
}
